﻿using EventModel;
using MassTransit;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ExamEventBus
{
    public class ExamEventJob : IJob
    {
        public IEventRepository _ExamEventRepository { get; }
        public IBusControl EventBus { get; }

        public ExamEventJob(IEventRepository ExamEventRepository, IConfiguration configuration)
        {
            this._ExamEventRepository = ExamEventRepository;
            this.EventBus = Startup.BusControl;
        }

        public Task Execute(IJobExecutionContext context)
        {
            var events = _ExamEventRepository.GetEvents().GetAwaiter().GetResult();

            if (events == null || events.Count() == 0)
            {
                Console.WriteLine($"没有可消费的消息");
            }

            if (events.Count() > 0)
            {
                foreach (var eventItem in events)
                {
                    IExamModel model = (IExamModel)eventItem;
                    string json = JsonConvert.SerializeObject(model);
                    new RedisHelper().Enqueue("阅卷入队列———examqueue", json);
                    //将消息添加到队列中
                    EventBus.Publish(model);
                }
            }
            return Task.CompletedTask;
        }
    }
}
